package com.duojuhe.security.shiro.filter;

import com.duojuhe.security.shiro.StatelessAuthenticationToken;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.utils.token.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 无须登录拦截
 */
@Slf4j
public class ShiroPublicControlFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws Exception {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        try {
            // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
           if (RequestMethod.OPTIONS.name().equals(request.getMethod().toUpperCase())) {
                response.setStatus(HttpStatus.OK.value());
                return false;
            }
            //token值
            String token = TokenUtils.getTokenByRequest(request);
            // 委托给Realm进行验证
            getSubject(request, response).login(new StatelessAuthenticationToken(token, SystemEnum.LOGIN_RESOURCE.VISITORS_USER.getKey()));
            return true;
        }catch (Exception e) {
            return true;
        }
    }
}
